package com.srwl.mytx.widget;

import android.app.Dialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.LoginActivity;
import com.srwl.mytx.domain.BizContent;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.fragment.BaseFragment;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.AliService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.MoneyInputCheck;
import com.srwl.mytx.R;
import com.srwl.mytx.utils.Utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class RechargeDialogFragment extends BaseFragment implements View.OnClickListener {
    private static String TAG = "RechargeDialogFragment";
    private Button mBtnPutMoney;
    private String mMoneyAmount;
    private EditText mEtMoneyAmount;
    private OnFragmentInteractionListener mListener;

    public static RechargeDialogFragment newInstance() {
        RechargeDialogFragment fragment = new RechargeDialogFragment();

        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_TITLE, R.style.RechargeDialogStyle);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recharge, container, false);
        initViewsAndEvents(view);
        return view;
    }


    protected void initViewsAndEvents(View view) {
        mBtnPutMoney = view.findViewById(R.id.btn_transfer);
        mBtnPutMoney.setOnClickListener(this);

        enableButton(false);

        mEtMoneyAmount = view.findViewById(R.id.et_transfer_money);


        MoneyInputCheck inputCheck = new MoneyInputCheck(getActivity(), 0.01, 10000D, new MoneyInputCheck.InteractionListener() {
            @Override
            public void showErrorMessage(String message) {
                mEtMoneyAmount.setError(message);
            }

            @Override
            public void waitInput() {
                enableButton(false);
            }

            @Override
            public void inputRight() {
                enableButton(true);
            }
        });

        mEtMoneyAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                inputCheck.onTextChanged(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
                inputCheck.afterTextChanged(s);
            }
        });

    }

    @Override
    public void onClick(View v) {


        if (v.getId() == R.id.btn_transfer) {
            if (!Helper.getInstance().isNetworkConnected()) {
                this.showToast_v1(getString(R.string.network_anomalies));
                return;
            }
            if (ClickUtil.isFastClick()) return;

            if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
                LoginActivity.startActivity(getActivity(), "充值前请先登录");
                return;
            }

            enableButton(false);
            mMoneyAmount = mEtMoneyAmount.getText().toString().trim();

            //   redPacketInfo.redPacketAmount = mMoneyAmount;
            // retryRPToken();

            BizContent bizContent = new BizContent();
            bizContent.setSubject("蚂蚁金币充值");
            bizContent.setTotalAmount(Double.valueOf(mMoneyAmount));
            bizContent.setBody("蚂蚁金币充值");
            bizContent.setProductCode("QUICK_MSECURITY_PAY");
            bizContent.setTimeoutExpress("30m");

            //请求服务端获取支付url
            RetrofitManager.getInstance().createRequest(AliService.class)
                    .getAlipayUrl(bizContent)
                    .enqueue(new Callback<CommonResult>() {
                        @Override
                        public void onResponse(Call<CommonResult> call, final Response<CommonResult> response) {
                            enableButton(true);
                            CommonResult result = response.body();
                            if (!response.isSuccessful() || result == null) {
                                Log.e(TAG, "支付出错 " + response.message());
                                showToast(getString(R.string.system_busy));
                                return;
                            }
                            if (result.isError()) {
                                Log.e(TAG, "支付出错 " + result.getMsg());

                                if (result.getStatus() == Constant.TOKEN_INVALID) {
                                    showToast(getString(R.string.login_expire));
                                }
                                return;
                            }
                            String alipayUrl = (String) result.getData();
                            Log.d(TAG, "支付链接：" + alipayUrl);
                            final String finalAlipayUrl = alipayUrl;
                            recharge(finalAlipayUrl);
                        }

                        @Override
                        public void onFailure(Call<CommonResult> call, Throwable t) {
                            enableButton(true);
                            t.printStackTrace();
                            Log.e(TAG, "支付出错 " + t.getMessage());
                        }
                    });

        }
    }

    private void recharge(String finalAlipayUrl) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> response = alipay.payV2(finalAlipayUrl, true);
                String resultStatus = response.get("resultStatus");
                String result1 = response.get("result");
                Log.d(TAG, "支付结果：" + result1);
                //   Map result = JSON.parseObject(response.get("result"), Map.class);
                switch (resultStatus) {
                    case "9000":
                        Log.i(TAG, "支付宝：订单支付完成");
                        break;
                    case "8000":
                        Log.e(TAG, "支付宝：正在处理中，支付结果未知（有可能已经支付成功）");
                        return;
                    case "6004":
                        Log.e(TAG, "支付宝：支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态");
                        return;
                    case "6002":
                        Log.e(TAG, "支付宝：网络连接出错");
                        return;
                    case "6001":
                        Log.e(TAG, "支付宝：用户中途取消");
                        return;
                    case "5000":
                        Log.e(TAG, "支付宝：重复请求");
                        return;
                    case "4000":
                        Log.e(TAG, "支付宝：订单支付失败");
                        return;
                    default:
                        Log.e(TAG, "支付宝：其他支付错误");
                        return;

                }

                String content = "";
                String sign = "";
                String rgex_content = "(?<=\"alipay_trade_app_pay_response\":).*?(?=,\"sign\":)";
                String rgex_sign = "(?<=\"sign\":\").*?(?=\")";
                Pattern pattern = Pattern.compile(rgex_content);// 匹配的模式
                Matcher m = pattern.matcher(result1);
                if (m.find()) {
                    content = m.group();
                }
                Pattern pattern1 = Pattern.compile(rgex_sign);
                Matcher matcher1 = pattern1.matcher(result1);
                if (matcher1.find()) {
                    sign = matcher1.group();
                }
                //这样的方式获取的content 顺序不对，验签过不了
//                                    JSONObject jsonObject = JSONObject.parseObject(result1);
//                                    content = jsonObject.getString("alipay_trade_app_pay_response");
//                                    sign = jsonObject.getString("sign");
                Log.d(TAG, "CONTENT:" + content);
                Log.d(TAG, "SIGN:" + sign);
                Map<String, String> map = new HashMap<>();
                map.put("content", content);
                map.put("sign", sign);
                validateSign(map, response);
//                                    Message msg = new Message();
//                                    msg.what = SDK_PAY_FLAG;
//                                    msg.obj = response;
//                                    mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    //去服务端验证签名
    private void validateSign(Map<String, String> info, final Map<String, String> aliResponse) {
        if (!Helper.getInstance().isNetworkConnected()){
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        JSONObject body = new JSONObject();
        body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
        body.put("ct", info);
        RetrofitManager.getInstance().createRequest(AliService.class)
                .alipayValidateSign(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "验证签名出错 " + response.message());
                            showToast("支付验证出错，请联系客服");
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "验证签名出错 " + result.getMsg());

                            if (result.getStatus() == Constant.VALIDATE_SIGN_FAIL) {
                                showToast("支付验证出错，请联系客服");
                            }
                            return;
                        }
                        Log.d(TAG, "验证签名成功 " + result.getMsg());

                        BigDecimal totalAmount = (BigDecimal) result.getData();
                        Double totalAmountDouble = totalAmount.setScale(2, RoundingMode.HALF_DOWN).doubleValue();// 保留两位小数， RoundingMode.HALF_DOWN 4舍5不入  ；RoundingMode.HALF_UP 4舍5入
                        if (mListener != null) {
                            mListener.onRechargeSuccess(totalAmountDouble);
                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "验证签名出错 " + t.getMessage());
                    }
                });
    }

    private void enableButton(boolean enable) {
        mBtnPutMoney.setEnabled(enable);
    }

    @Override
    public void onResume() {
        super.onResume();
        getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, screenHeight / 2);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);

        dialog.setCanceledOnTouchOutside(true);
        // 设置宽度为屏宽、靠近屏幕底部。
        Window window = dialog.getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        wlp.height = screenHeight / 2;
        window.setAttributes(wlp);
        return dialog;

    }


    public void setOnFragmentInteractionListener(OnFragmentInteractionListener listener) {
        this.mListener = listener;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onRechargeSuccess(Double totalBalance);

        void showToast(String message);
    }

}
